package org.orbis.communicate.lock;

import org.orbis.logging.LogParser;

/**
 * <p>
 * This class works globally, to control index stream in local.
 * </p>
 * <p>
 * You should call {@link #initialize()} to initialize an index state and lock
 * object, or static methods in the class will not work well or you could see
 * {@link NullPointerException}.
 * </p>
 * @author iamyusk
 */
public class IndexableSwitch{
	private static boolean indexable;
	private static volatile Object lockObj;

	public static void initialize(){
		indexable = true;
		lockObj = new Object();
	}

	public static boolean isIndexable(){
		return indexable;
	}

	public static void lock(){
		indexable = false;
		LogParser.fine("Index LOCKED");
	}

	public static void waitIfLocked() throws InterruptedException{
		if(!indexable){
			synchronized(lockObj){
				lockObj.wait();
			}
		}
	}

	public static void unlock() throws InterruptedException{
		synchronized(lockObj){
			lockObj.notifyAll();
		}
		indexable = true;
		LogParser.fine("Index UNLOCKED");
	}
}
